package cn.itcast.openai;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author wys
 * @version V1.0
 * @date 2025-04-19 17:43
 */
public class CompletionsMultipleRoundsDemo {
    private static OpenAIClient client;

    public static void main(String[] args) {
        client = OpenAIOkHttpClient.builder()
                // .baseUrl("https://api.chatanywhere.tech/v1")
                // .apiKey(System.getenv("OPENAI_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .build();
        var messageParamList = new ArrayList<ChatCompletionMessageParam>();
        chat("我是大蠢驴,记住我", messageParamList);
        chat("我是谁", messageParamList);
    }

    private static void chat(String userMessage, List<ChatCompletionMessageParam> messageParamList) {
        messageParamList.add(ChatCompletionMessageParam.ofUser(ChatCompletionUserMessageParam.builder()
                .content(userMessage).build()));

        ChatCompletionCreateParams createParams = ChatCompletionCreateParams.builder()
                .model("qwen-plus")
                .messages(messageParamList)
                .build();

        client.chat().completions()
                .create(createParams)
                .choices()
                .stream()
                .flatMap(
                        choice -> {
                            Optional<String> content = choice.message().content();
                            content.ifPresent(s -> messageParamList.add(ChatCompletionMessageParam.ofAssistant(ChatCompletionAssistantMessageParam.builder()
                                    .content(s).build())));
                            return content.stream();
                        }
                )
                .forEach(System.out::println);
    }
}
